package com.coyote.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

@Component
public class LoggingGlobalFilter implements GlobalFilter, Ordered {

    public static final String GATEWAY_REQUEST_URL_ATTR = "gatewayRequestUrl";

    private static final Logger log = LoggerFactory.getLogger(LoggingGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 记录请求信息
        ServerHttpRequest request = exchange.getRequest();
        log.warn("请求路径: {}", request.getPath());
        log.warn("请求方法: {}", request.getMethod());
        log.warn("请求头: {}", request.getHeaders());

        // 获取转发的目标URI
//        String targetUri = getTargetUri(exchange);
//        if (targetUri != null) {
//            log.warn("请求将转发至: {}", targetUri);
//        }

        // 继续执行链中的下一个过滤器
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 可以在这里记录响应信息
            log.warn("响应状态: {}", exchange.getResponse().getStatusCode());
        }));
    }

//    private String getTargetUri(ServerWebExchange exchange) {
//        // 尝试从属性中获取目标URI
//        Object uriObj = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
//        if (uriObj instanceof URI) {
//            return ((URI) uriObj).toString();
//        }
//        return null;
//    }

    @Override
    public int getOrder() {
        // 设置过滤器的顺序，值越小优先级越高
        return -100;
    }
}